//
//  CTCFinanceTaxCircleVC.m
//  ConsultantVersion
//
//  Created by 李小龙 on 2017/3/25.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "CTCMyArticleVC.h"
#import "CTCArticleListCell.h"
#import "CTCArticleDetailVC.h"
#import "CTCArticleModel.h"
#import "CTCArticleModel.h"
#import "CTCPublishArticleVC.h"
#import "MXScrollView.h"
@interface CTCMyArticleVC ()<MXSegmentedPagerDelegate,
                                    MXSegmentedPagerDataSource,
                                    MXScrollViewDelegate,
                                    MXScrollViewDelegate,
                                    UITableViewDelegate,
                                    UITableViewDataSource
                                    >

@property (nonatomic, strong) MXSegmentedPager  * segmentedPager;
@property (nonatomic, strong) UITableView       * firstTableView;
@property (nonatomic, strong) UITableView       * secondTableView;
//@property (nonatomic, strong) UITableView       * tableView;
@property (nonatomic, strong) UIWebView        * webView;
/** <#strong属性注释#> */
//@property (nonatomic, strong) NSMutableArray *articleArr;

/** <#strong属性注释#> */
@property (nonatomic, strong) NSMutableArray *firstArticleArr;

/** <#strong属性注释#> */
@property (nonatomic, strong) NSMutableArray *secondArticleArr;

///** <#assign属性注释#> */
//@property (nonatomic, assign) NSInteger lastID;

/** <#assign属性注释#> */
@property (nonatomic, assign) NSInteger firstLastID;

/** <#assign属性注释#> */
@property (nonatomic, assign) NSInteger secondLastID;


@end

@implementation CTCMyArticleVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = HEXCOLOR(0xF9F9F9);
//    [self setupNav];
    self.firstLastID = 1;
    self.secondLastID = 1;
    self.title = @"我的文章";
    [self.view addSubview:self.segmentedPager];
    
    [self loadNew];
}



- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    self.segmentedPager.frame = (CGRect){
        .origin.x       = 0.f,
        .origin.y       = 0.f,
        .size.width     = self.view.frame.size.width,
        .size.height    = self.view.frame.size.height
    };
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark <MXSegmentedPagerDelegate>

- (CGFloat)heightForSegmentedControlInSegmentedPager:(MXSegmentedPager *)segmentedPager {
    return 50;
}

- (void)segmentedPager:(MXSegmentedPager *)segmentedPager didSelectViewWithTitle:(NSString *)title {
        NSLog(@"%ld page selected.", (long)segmentedPager.segmentedControl.selectedSegmentIndex);
    if ((segmentedPager.segmentedControl.selectedSegmentIndex == 1) && !(self.secondArticleArr.count)) {
        [self loadNew];
    }
}

- (void)segmentedPager:(MXSegmentedPager *)segmentedPager didScrollWithParallaxHeader:(MXParallaxHeader *)parallaxHeader {
        NSLog(@"progress %f", parallaxHeader.progress);
    
}

#pragma mark <MXSegmentedPagerDataSource>

- (NSInteger)numberOfPagesInSegmentedPager:(MXSegmentedPager *)segmentedPager {
    return 2;
}

- (NSString *)segmentedPager:(MXSegmentedPager *)segmentedPager titleForSectionAtIndex:(NSInteger)index {
    
     return @[@"财税资讯", @"新政解读"][index];
}

- (UIView *)segmentedPager:(MXSegmentedPager *)segmentedPager viewForPageAtIndex:(NSInteger)index {

    
    if (index == 0) {
        return self.firstTableView;
    } else {
        return self.secondTableView;
    }
}

#pragma mark <UITableViewDelegate>

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CTCArticleListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CTCArticleListCell" forIndexPath:indexPath];
    if (self.segmentedPager.segmentedControl.selectedSegmentIndex == 0) {
        cell.articleModel = self.firstArticleArr[indexPath.row];
    } else {
        cell.articleModel = self.secondArticleArr[indexPath.row];
    }
    
    return cell;
}


#pragma mark <UITableViewDataSource>

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.segmentedPager.segmentedControl.selectedSegmentIndex == 0) {
        return self.firstArticleArr.count;
    } else {
        return self.secondArticleArr.count;
    }
    
}




- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CTCArticleDetailVC *detailVC = [CTCArticleDetailVC viewControllerFromStoryboard];
    detailVC.isFromMyArticleVC = YES;
    CTCArticleModel *model;
    if (self.segmentedPager.segmentedControl.selectedSegmentIndex == 0) {
        model = self.firstArticleArr[indexPath.row];
       
    }else {
        model = self.secondArticleArr[indexPath.row];
    }
    
    detailVC.articleModel = model;
    
    MPWeakSelf(self);
    detailVC.commentSuccessReturnBlcok = ^(){
        model.discussNum = model.discussNum + 1;
        if (weakself.segmentedPager.segmentedControl.selectedSegmentIndex == 0) {
            [weakself.firstTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
        } else {
            [weakself.secondTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
        }
    };
    
    detailVC.deleteMyArticleBlcok = ^(){
       
        if (weakself.segmentedPager.segmentedControl.selectedSegmentIndex == 0) {
            [weakself.firstArticleArr removeObject:model];
            [weakself.firstTableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationTop];
        } else {
            [weakself.secondArticleArr removeObject:model];
            [weakself.secondTableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationTop];
        }
    };
    
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)loadNew
{
    
    if (self.segmentedPager.segmentedControl.selectedSegmentIndex == 0) {
        self.firstLastID = 1;
        [self.firstArticleArr removeAllObjects];
        
    } else {
       self.secondLastID = 1;
       [self.secondArticleArr removeAllObjects];
    }
    
    [self loadArticleListData];
}

- (void)loadMore
{
    DeLog(@"更多请求");
    [self loadArticleListData];
}


- (void)stopRefresh
{
    if (self.segmentedPager.segmentedControl.selectedSegmentIndex == 0) {
        !self.firstTableView.mj_header.isRefreshing ? : self.firstTableView.mj_header.endRefreshing;
        !self.firstTableView.mj_footer.isRefreshing ? : self.firstTableView.mj_footer.endRefreshing;
    }
    else {
        !self.secondTableView.mj_header.isRefreshing ? : self.secondTableView.mj_header.endRefreshing;
        !self.secondTableView.mj_footer.isRefreshing ? : self.secondTableView.mj_footer.endRefreshing;
    }
   
}


- (void)loadArticleListData
{
    
    NSMutableDictionary *paramDic = [NSMutableDictionary dictionary];
    
    paramDic[@"type"] = @"label";
    if (self.segmentedPager.segmentedControl.selectedSegmentIndex == 0) {
        paramDic[@"uuid"] = @"1";
        paramDic[@"pageIndex"] = @(self.firstLastID);
        paramDic[@"pageEnd"] = @(self.firstLastID+9);
    } else {
        paramDic[@"uuid"] = @"2";
        paramDic[@"pageIndex"] = @(self.secondLastID);
        paramDic[@"pageEnd"] = @(self.secondLastID+9);
    }
    
    DeLog(@"网络请求,当前的index:%ld, 请求参数:%@",(long)self.segmentedPager.segmentedControl.selectedSegmentIndex,paramDic);
    [MBProgressHUD showAnimationHUD];
    [RequestTool POST:kMyPublicedArticleUrl parameters:paramDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DeLog(@"responseObject:%@",responseObject);
        [self stopRefresh];
        CTCArticleListModel *listModel = [CTCArticleListModel yy_modelWithJSON:responseObject];
        if ([listModel.code integerValue] == 1) {
            [MBProgressHUD hideHUD];

            if (self.segmentedPager.segmentedControl.selectedSegmentIndex == 0) {
                
                if (!listModel.articleArr.count) {
                    self.firstTableView.mj_footer.state = MJRefreshStateNoMoreData;
                    return ;
                }
                
                [self.firstArticleArr addObjectsFromArray:listModel.articleArr];
                self.firstLastID += self.firstArticleArr.count;
                [self.firstTableView reloadData];
                
            } else {
                
                if (!listModel.articleArr.count) {
                    self.secondTableView.mj_footer.state = MJRefreshStateNoMoreData;
                    return ;
                }
                
                [self.secondArticleArr addObjectsFromArray:listModel.articleArr];
                self.secondLastID += self.secondArticleArr.count;
                [self.secondTableView reloadData];
            }
            
        } else {
            [MBProgressHUD showErrorMessage:listModel.des];
            if ([listModel.code integerValue] == 2) {
                CTCLoginViewController *vc = [CTCLoginViewController viewControllerFromStoryboard];
                MPWeakSelf(self);
                vc.loginSuccess = ^(){
                    [weakself loadNew];
                };
                [self presentViewController:vc animated:YES completion:nil];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"error:%@",error);
        [self stopRefresh];
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [MBProgressHUD showErrorMessage:@"网络不给力"];
        }
        else {
            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
        }

    }];
}

- (void)setupNav
{
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发布" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemClick)];
}


- (void)rightBarButtonItemClick
{
    CTCPublishArticleVC *vc = [[CTCPublishArticleVC alloc]init];
    CTCNavigationController *nav = [[CTCNavigationController alloc]initWithRootViewController:vc];
    MPWeakSelf(self);
    vc.pulicSuccessDismissBlock = ^(NSString *typeString){
        [weakself loadNew];
    };
    [self presentViewController:nav animated:YES completion:nil];
}




- (MXSegmentedPager *)segmentedPager {
    if (!_segmentedPager) {
        _segmentedPager = [[MXSegmentedPager alloc] init];
        _segmentedPager.segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
        _segmentedPager.segmentedControl.backgroundColor = [UIColor whiteColor];
        _segmentedPager.segmentedControl.selectionIndicatorHeight = 2;
        _segmentedPager.segmentedControl.titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor blackColor], NSFontAttributeName:[UIFont boldSystemFontOfSize:14]};
        _segmentedPager.segmentedControl.selectedTitleTextAttributes = @{NSForegroundColorAttributeName : HEXCOLOR(0x2079ef), NSFontAttributeName:[UIFont boldSystemFontOfSize:14]};
        _segmentedPager.segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleFullWidthStripe;
        _segmentedPager.segmentedControl.selectionIndicatorColor = HEXCOLOR(0x2079ef);
        _segmentedPager.bounces = NO;
        _segmentedPager.delegate    = self;
        _segmentedPager.dataSource  = self;
        [_segmentedPager.pager registerClass:[self.firstTableView class] forPageReuseIdentifier:@"tableView"];
    }
    return _segmentedPager;
}



- (UITableView *)firstTableView
{
    if (!_firstTableView) {
        _firstTableView = [[UITableView alloc] init];
        _firstTableView.delegate = self;
        _firstTableView.dataSource = self;
        _firstTableView.backgroundColor = HEXCOLOR(0xF9F9F9);
        _firstTableView.rowHeight = UITableViewAutomaticDimension;
        _firstTableView.estimatedRowHeight = 200;
        _firstTableView.showsVerticalScrollIndicator = YES;
        _firstTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        
        [_firstTableView registerNib:[UINib nibWithNibName:@"CTCArticleListCell" bundle:nil] forCellReuseIdentifier:@"CTCArticleListCell"];
        _firstTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNew)];
        _firstTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    }
    
    return _firstTableView;
}


- (UITableView *)secondTableView
{
    if (!_secondTableView) {
        _secondTableView = [self.segmentedPager.pager dequeueReusablePageWithIdentifier:@"tableView"];
        _secondTableView.delegate = self;
        _secondTableView.dataSource = self;
        _secondTableView.backgroundColor = HEXCOLOR(0xF9F9F9);
        _secondTableView.rowHeight = UITableViewAutomaticDimension;
        _secondTableView.estimatedRowHeight = 200;
        _secondTableView.showsVerticalScrollIndicator = NO;
        _secondTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        
        [_secondTableView registerNib:[UINib nibWithNibName:@"CTCArticleListCell" bundle:nil] forCellReuseIdentifier:@"CTCArticleListCell"];
        //
        _secondTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNew)];
        _secondTableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    }
    
    return _secondTableView;
}



-(NSMutableArray *)firstArticleArr
{
    if (!_firstArticleArr) {
        _firstArticleArr = [NSMutableArray array];
    }
    
    return _firstArticleArr;
}


-(NSMutableArray *)secondArticleArr
{
    if (!_secondArticleArr) {
        _secondArticleArr = [NSMutableArray array];
    }
    
    return _secondArticleArr;
}

@end
